package com.mofang.powerdekorhelper.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.telephony.TelephonyManager;
import android.text.format.DateUtils;
import android.util.Log;

import com.mofang.powerdekorhelper.base.BaseApplication;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * Created by luofei on 2016/7/11 0011.
 */
public class AppUtils {

    /**
     * 获取设备唯一标识
     *
     * @param context
     * @return
     */
    public static String getDeviceSerialNumber(Context context) {

        StringBuilder deviceId = new StringBuilder();

        String str1 = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);

        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        String iMei = tm.getDeviceId();

        String serialNumber = tm.getSimSerialNumber();

        String softwareVersion = tm.getDeviceSoftwareVersion();

        int phoneType = tm.getPhoneType();

        int networkType = tm.getNetworkType();


        if (iMei != null && !iMei.equals("")) {
            deviceId.append(iMei);
            if (serialNumber != null && !serialNumber.equals("")) {
                deviceId.append(serialNumber);
            } else {
                T.showShort(context, "获取设备序列号失败");
            }

        } else {
            T.showShort(context, "获取设备imei失败");
        }

        return serialNumber;
    }

    /**
     * 获取Android设备的mac号
     */
    @NonNull
    public static String getLocalMacAddress() {
        String Mac = null;
        try {
            String path = "sys/class/net/wlan0/address";
            if ((new File(path)).exists()) {
                FileInputStream fis = new FileInputStream(path);
                byte[] buffer = new byte[8192];
                int byteCount = fis.read(buffer);
                if (byteCount > 0) {
                    Mac = new String(buffer, 0, byteCount, "utf-8");
                }
            }
            //L.e("MacAddress","MacAddress------------------>"+Mac);

            if (Mac == null || Mac.length() == 0) {
                path = "sys/class/net/eth0/address";
                FileInputStream fis_name = new FileInputStream(path);
                byte[] buffer_name = new byte[8192];
                int byteCount_name = fis_name.read(buffer_name);
                if (byteCount_name > 0) {
                    Mac = new String(buffer_name, 0, byteCount_name, "utf-8");
                }
            }

            // L.e("MacAddress","MacAddress------------------>"+Mac);

            if (Mac.length() == 0 || Mac == null) {
                return "";
            }
        } catch (Exception io) {
            Log.v("daming.zou**exception*", "" + io.toString());
        }

        Log.v("xulongheng*Mac", Mac);
        Mac = Mac.trim();
        String mac[] = Mac.split(":");
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < mac.length; i++) {
            buffer = buffer.append(mac[i]);
        }
        return buffer.toString();

    }


    /**
     * 获取系统当前时间
     *
     * @param context
     * @return
     */
    public static String getCurrentTime(Context context) {
        String currentTime = DateUtils.formatDateTime(context, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
                | DateUtils.FORMAT_ABBREV_ALL);
        return currentTime;

    }

    /**
     * 检测网络是否可用
     *
     * @return
     */
    public static boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) BaseApplication.application.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnectedOrConnecting();
    }

    /**
     * 获取当前网络类型
     *
     * @return 0：没有网络   1：WIFI网络   2：WAP网络    3：NET网络
     */

    public static final int NETTYPE_WIFI = 0x01;
    public static final int NETTYPE_CMWAP = 0x02;
    public static final int NETTYPE_CMNET = 0x03;

    public static int getNetworkType() {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) BaseApplication.application.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            String extraInfo = networkInfo.getExtraInfo();
            if (extraInfo != null && !extraInfo.equals("")) {
                if (extraInfo.toLowerCase().equals("cmnet")) {
                    netType = NETTYPE_CMNET;
                } else {
                    netType = NETTYPE_CMWAP;
                }
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = NETTYPE_WIFI;
        }
        return netType;
    }

    // get versioncode
    public static int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
        }
        return versionCode;
    }

    // get versionName
    public static String getVersionName(Context context) {
        String versionName = null;
        try {
            versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
        }

        return versionName;
    }

    public static Bitmap getQrCode(String url, String str) {
        Bitmap bitmap = null;

        try {
            URL urls = new URL(url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) urls.openConnection();
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");


            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            dos.writeBytes(str);
            dos.flush();

            // 读取服务器返回结果

            InputStream is = httpURLConnection.getInputStream();

//          saveImgInStream(is);

            bitmap = BitmapFactory.decodeStream(is);

            dos.close();
            is.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    public static String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) BaseApplication.getApplication().getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = BaseApplication.getApplication().getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                L.d("initEMOptions", "Error>> :" + e.toString());
            }
        }
        return processName;
    }


    /**
     * 判断当前应用程序处于前台还是后台
     */
    public static boolean isAppAlive(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return false;
            }
        }
        return true;

    }

}
